package test.test2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket = null;

    public Server(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");
        ExecutorService threadPool = Executors.newCachedThreadPool();
        while (true) {
            // 使用这个对象和具体的客户端进行交流
            Socket clientSocket = serverSocket.accept();

            // 使用线程池
            threadPool.submit(() -> {
                processConnection(clientSocket);
            });
        }
    }

    // 使用这个方法来处理一个连接
    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端上线\n",
                clientSocket.getInetAddress().toString(),
                clientSocket.getPort()
        );

        // 基于 socket 对象和客户端进行通信
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 由于要处理多个请求和响应, 使用循环来进行
            while (true) {
                // 1. 读取请求
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    // 没有下个数据, 说明读完了. (客户端关闭了连接)
                    System.out.printf("[%s:%d] 客户端下线\n",
                            clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                // 2. 根据请求构造响应
                String response = process(request);
                // 3. 返回响应结果
                PrintWriter printWriter = new PrintWriter(outputStream);
                // 使用 println 来写入, 让结果中带有换行, 方便对端进行接续
                printWriter.println(response);
                // 刷新缓冲区, 保证当前的数据确实发送出去了
                printWriter.flush();

                System.out.printf("[%s:%d] req: %s; resp: %s \n",
                        clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),
                        request,
                        response
                );
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String process(String request) {
        String textData = null;
        String timestamp = null;
        try (
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/communication_db", "root", "000000");
                Statement statement = connection.createStatement()
        ) {
            textData = request;
            timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 存储数据到数据库
            String sql = "insert into communication_table (text_data, timestamp) values ('" + textData + "', '" + timestamp + "')";
            statement.executeUpdate(sql);

            return "接收到客户端数据:" + textData + "," + "数据已存储到数据库,时间戳" + timestamp;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        Server tcpEchoServer = new Server(8888);
        tcpEchoServer.start();
    }
}
